package com.innovation.ic.im.end.base.handler.im_erp9;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.innovation.ic.im.end.base.model.im_erp9.ChatPair;
import com.innovation.ic.im.end.base.model.im_erp9.Message;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Set;

/**
 * message处理类
 */
@Component
public class MessageHandler extends ImErp9AbstractHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 处理im-erp9数据库的message表的insert操作
     * @param message 插入的数据
     */
    public void handleInsertMessage(Message message) {
        logger.info("处理im-erp9数据库的message表的insert操作，向redis插入MESSAGE:开头的数据");

        ChatPair chatPair = getChatPairByAccount(message.getFromUserAccount(), message.getToUserAccount());
        if(chatPair != null && chatPair.getCode() != null){
            // 向redis存储数据
            String key = RedisStorage.MESSAGE_PREFIX +  chatPair.getCode();
            String value = JSONObject.toJSONString(message);
            double score = message.getCreateTime().getTime();
            redisManager.zAdd(key, value, score);
            //redisManager.expire(key, redisParamConfig.getTimeout());
        }else{
            logger.info("根据fromUserAccount:[{}],toUserAccount:[{}]未查询到聊天对信息,跳过当前数据处理", message.getFromUserAccount(), message.getToUserAccount());
        }
    }

    /**
     * 处理im-erp9数据库的message表的update操作
     * @param message 更新的数据
     */
    public void handleUpdateMessage(Message message) {
        logger.info("处理im-erp9数据库的message表的update操作，更新redis中MESSAGE:开头的数据");
        ChatPair chatPair = getChatPairByAccount(message.getFromUserAccount(), message.getToUserAccount());
        if(chatPair != null && chatPair.getCode() != null){
            String key = RedisStorage.MESSAGE_PREFIX +  chatPair.getCode();
            double score = message.getCreateTime().getTime();
            Set<String> stringSet = redisManager.zReverseRangeByScore(key, score, score);
            if(stringSet != null && stringSet.size() > 0){
                for(String msg : stringSet){
                    JSONObject jsonObject = JSONObject.parseObject(msg);
                    if((jsonObject.get(Constants.ID)).toString().equals(message.getId().toString())){
                        // 删除redis中的值
                        redisManager.zRemove(key, msg);
                        // 添加新的值
                        String value = JSONObject.toJSONString(message);
                        redisManager.zAdd(key, value, score);
                        break;
                    }
                }
            }
        }else{
            logger.info("根据fromUserAccount:[{}],toUserAccount:[{}]未查询到聊天对信息,跳过当前数据处理", message.getFromUserAccount(), message.getToUserAccount());
        }
    }

    /**
     * 根据账号查找聊天对数据
     * @param fromUserAccount 发送消息的用户账号
     * @param toUserAccount 接收消息的用户账号
     * @return 返回聊天对信息
     */
    private ChatPair getChatPairByAccount(String fromUserAccount, String toUserAccount){
        // 查找chat_pair表中的code_
        ChatPair chatPair = new ChatPair();
        chatPair.setFromUserAccount(fromUserAccount);
        chatPair.setToUserAccount(toUserAccount);
        QueryWrapper<ChatPair> queryWrapper = new QueryWrapper<>(chatPair);
        return chatPairMapper.selectOne(queryWrapper);
    }
}